package dao;

import pojo.Product;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDAO {

    private static final String TABLE_NAME = "tb_products";

    // 删除商品
    public static void deleteProduct(int id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        JDBCUtils.execute(sql, id);
    }

    // 更新商品信息
    public static void updateProduct(Product product) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET name = ?, description = ?, img = ? WHERE id = ?";
        JDBCUtils.execute(sql, product.getName(), product.getDescription(), product.getImg(), product.getId());
    }

    // 添加商品
    public static void addProduct(Product product) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (name, description, img) VALUES (?, ?, ?)";
        JDBCUtils.execute(sql, product.getName(), product.getDescription(), product.getImg());
    }

    // 获取所有商品
    public static List<Product> getAllProducts() throws SQLException {
        List<Product> products = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Product product = createProductFromResultSet(resultSet);
            products.add(product);
        }
        return products;
    }

    // 根据ID获取商品
    public static Product getProductById(int id) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, id);
        if (resultSet.next()) {
            return createProductFromResultSet(resultSet);
        }
        return null;
    }

    // 创建Product对象从ResultSet
    private static Product createProductFromResultSet(ResultSet resultSet) throws SQLException {
        Integer id = resultSet.getInt("id");
        String name = resultSet.getString("name");
        String description = resultSet.getString("description");
        String img = resultSet.getString("img");

        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setDescription(description);
        product.setImg(img);

        return product;
    }
}
